package libraries

import (
		"sync"
	"github.com/astaxie/beego"

	"gopkg.in/mgo.v2"
	"fmt"
)
type MongoDB struct {
	collection *mgo.Collection
	database *mgo.Database
}

var (
	mgoDb *mgo.Session

	host = beego.AppConfig.String("mongo_host")
	database = beego.AppConfig.String("mongo_database")

	//host = "192.168.10.10:27017"
	//database = "test"

	lock *sync.Mutex = &sync.Mutex{}
	
)

func (this *MongoDB) Init(){

}

//连接db生成session会话
func (this *MongoDB) ConnectDb() *mgo.Session {
	lock.Lock()
	fmt.Printf(host)

	defer lock.Unlock()
	var err error
	if mgoDb == nil {
		mgoDb, err = mgo.Dial(host)
		if err != nil {
			panic(err)
		}
	}

	return mgoDb
}

//获取集合资源
func (this *MongoDB) SetCollection(collectionName string) *mgo.Collection {
	dbSession := this.ConnectDb()
	//this.collection = dbSession.DB(database).C(collectionName)
	fmt.Printf(database)

	return dbSession.DB(database).C(collectionName)
}


/*
//获取集合内数据总数
func (this *MongoDB) GetCount() int {
	count, err := this.collection.Count()
	if err != nil {
		panic(err)
	}

	return count
}



//新增数据
func (this *MongoDB) InsertData(data ... interface{}) error {
	return this.collection.Insert(data)
}

//查找所有数据
func (this *MongoDB) FindAllData(where interface{}) *mgo.Iter {
	f := make(map[string]interface{})
	f["title"] = "123"
	return this.collection.Find(f).Iter()
}


//查找所有数据
func (this *MongoDB) Test() int {
	f := make(map[string]interface{})
	f["title"] = "123"
	count, err := this.collection.Find(f).Count()
	if err != nil{
		panic(err)
	}
	return count
}

//查找一条数据
func (this *MongoDB) FindData(where map[string]interface{}, result interface{}) {
	err := this.collection.Find(where).One(&result)
	if err != nil {
		panic(err)
	}
}

//更新数据
func (this *MongoDB) UpdateData(where map[string]interface{}, data map[string]interface{}) error {
	return this.collection.Update(where, data)
}

//删除符合where的一条数据
func (this *MongoDB) RemoveData(where map[string]interface{}) error {
	return this.collection.Remove(where)
}

//删除符合where的所有数据
func (this *MongoDB) removeAllData(where map[string]interface{}) error {
	_, err := this.collection.RemoveAll(where)
	return err
}*/